<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;


use think\Log;


//消息通知
class Wunews extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();

    }

    //'庫存不足','溫濕度通知','馬達運轉','其它'

    //每日08:55 触发 庫存不足
    //http://wu.test/api/wunews/checkkubz
    //http://59.120.82.54/api/wunews/checkkubz
    //http://wu.com/index.php/api/wunews/checkkubz
    public function checkkubz()
    {
        $notifyoption = \app\admin\model\wu\Notifyoption::get(1);
        if (!$notifyoption) {
            $this->error("无设置！");
        }

//        if ($notifyoption->kc_tzswitch == 0) {
//            $this->error("庫存通知已关闭！");
//        }

        $list = \app\admin\model\wu\Stockproductspec::with(['productspec'])
            ->where('productspec.hgs', 2)
            ->where("num < minnum")
            ->select();
        $list = collection($list)->toArray();
        foreach ($list as $row) {
            $news = new \app\admin\model\wu\News;
            $news->name = "[庫存不足]" . $row['productspec']['name'] . " 目前庫存: " . $row['num'];
            $news->type = "庫存不足";
            $news->save();
        }
        $this->success("ok");
    }

    //製程工序進出站 每天早上 9 點與下午 2 點
    //每日08:59 触发  13:59
    //定時任務，早上9點，提示前一天2點之後到早上9點前的工序打卡；下午2點，提示上午9點到下午2點間的工序打卡
    //http://wu.com:83/api/wunews/zzgx
    public function zzgx()
    {
        $notifyoption = \app\admin\model\wu\Notifyoption::get(1);
        if (!$notifyoption) {
            $this->error("无设置！");
        }

//        if ($notifyoption->zld_tzswitch == 0) {
//            $this->error("製令單通知已关闭！");
//        }
//        $today = date("Y-m-d H:i:s", time());
        $today = date("Y-m-d", time());
        $yesterday = date("Y-m-d", time() - 24 * 3600);
        $thistime = date("H:i:s", time());
        $from = $today . " 09:00:00";
        if ($thistime < "12:00:00") {
            $from = $yesterday . " 14:00:00";
        }

        $list = \app\admin\model\wu\Procedurestatelog::where('create_time', '>', $from)->select();
        $news = new \app\admin\model\wu\News;
        $news->type = "其它";
        $msg = "[製程工序]";
        //製令單號、規格、數量、工序，打卡時間
        $i = 1;
        foreach ($list as $row) {
            $workorder = \app\admin\model\wu\Workorder::get($row->workorder_id);
            if (!$workorder) {
                continue;
            }
            $productspec = \app\admin\model\wu\Productspec::get($workorder->productspec_id);
            if (!$productspec) {
                continue;
            }
            $procedure = \app\admin\model\wu\Procedure::get($row->procedure_id);
            if (!$procedure) {
                continue;
            }

            //$notifyoption.zld_tzpx
            if (false !== strpos($notifyoption->zld_tzpx, $procedure->name)) {
                continue;
            }

            $msg .= "\n" . $i . ".[" . $row->msg . "] [製令單號:" . $workorder->ordernumber . "] [規格:" . $productspec->name . "] [數量:" . $row->num . "] [工序:" . $procedure->name . "] [打卡時間:" . $row->update_time . "]";
            $i++;
        }

        if ($list && count($list) > 0) {
            $news->name = $msg;
            $news->save();
        }

        $this->success("ok");
    }

    //環境溫濕度 每分鐘判斷一次
    //http://wu.test/api/wunews/wenshidu
    public function wenshidu()
    {
        $hjdevice = \app\admin\model\wu\Hjdevice::get(2);
        if (!$hjdevice) {
            $this->error("无環境溫濕度装置！");
        }

        $notifyoption = \app\admin\model\wu\Notifyoption::get(1);
        if (!$notifyoption) {
            $this->error("无设置！");
        }

//        if ($notifyoption->wsd_tzswitch == 0) {
//            $this->error("環境溫濕度通知已关闭！");
//        }

        $wd_from = $notifyoption->wsd_lxwd - $notifyoption->wsd_wdfw;
        $wd_to = $notifyoption->wsd_lxwd + $notifyoption->wsd_wdfw;

        if ($hjdevice->wd_newvalue < $wd_from || $hjdevice->wd_newvalue > $wd_to) {
            //超出范围
            $news = new \app\admin\model\wu\News;
            $news->name = "[溫度報警]" . $hjdevice->wd_newvalue . "  （" . $wd_from . "～" . $wd_to . ")";
            $news->type = "溫濕度通知";
            $news->save();
        }

        $sd_from = $notifyoption->wsd_lxsd - $notifyoption->wsd_sdfw;
        $sd_to = $notifyoption->wsd_lxsd + $notifyoption->wsd_sdfw;

        if ($hjdevice->sd_newvalue < $sd_from || $hjdevice->sd_newvalue > $sd_to) {
            //超出范围
            $news = new \app\admin\model\wu\News;
            $news->name = "[濕度報警]" . $hjdevice->sd_newvalue . "  （" . $sd_from . "～" . $sd_to . ")";
            $news->type = "溫濕度通知";
            $news->save();
        }

        $this->success("ok");
    }

    //馬達不運轉 每分鐘判斷一次
    //http://wu.com:83/api/wunews/mdyz
    public function mdyz()
    {
        $hjdevice = \app\admin\model\wu\Hjdevice::get(3);
        if (!$hjdevice) {
            $this->error("无油量溢位與馬達運作監控裝置！");
        }

        $notifyoption = \app\admin\model\wu\Notifyoption::get(1);
        if (!$notifyoption) {
            $this->error("无设置！");
        }

//        if ($notifyoption->md_tzswitch == 0) {
//            $this->error("馬達不運轉通知已关闭！");
//        }
        //1分钟内，告警3次； 20秒1次
        $from = date("Y-m-d H:i:s", time() - 80);
        //循環過濾油箱 A1
        $md1num = \app\admin\model\wu\Hjdevicelog::where("commandtype", "FE08")
            ->where('value1', 0)
            ->where('create_time', '>', $from)
            ->where('hjdevice_id', 3)
            ->order('id desc')
            ->count();

        if ($md1num >= 3) {
            $news = new \app\admin\model\wu\News;
            $news->name = "[循環過濾油箱A1] 告警";
            $news->type = "馬達運轉";
            $news->save();
        }
//        echo $md1num;

        //循環過濾油箱 A1
        $md2num = \app\admin\model\wu\Hjdevicelog::where("commandtype", "FE08")
            ->where('value1', 1)
            ->where('create_time', '>', $from)
            ->where('hjdevice_id', 3)
            ->order('id desc')
            ->count();

        if ($md2num >= 3) {
            $news = new \app\admin\model\wu\News;
            $news->name = "[循環過濾油箱A2] 告警";
            $news->type = "馬達運轉";
            $news->save();
        }

        //第一集油箱B1
        $md3num = \app\admin\model\wu\Hjdevicelog::where("commandtype", "FE08")
            ->where('value1', 2)
            ->where('create_time', '>', $from)
            ->where('hjdevice_id', 3)
            ->order('id desc')
            ->count();

        if ($md3num >= 3) {
            $news = new \app\admin\model\wu\News;
            $news->name = "[第一集油箱B1] 告警";
            $news->type = "馬達運轉";
            $news->save();
        }

        //第一集油箱B4
        $md3num = \app\admin\model\wu\Hjdevicelog::where("commandtype", "FE08")
            ->where('value1', 3)
            ->where('create_time', '>', $from)
            ->where('hjdevice_id', 3)
            ->order('id desc')
            ->count();

        if ($md3num >= 3) {
            $news = new \app\admin\model\wu\News;
            $news->name = "[第一集油箱B4] 告警";
            $news->type = "馬達運轉";
            $news->save();
        }


//        $this->success($md1num);
    }

    //監控感測器 每分鐘判斷一次
    //http://wu.com:83/api/wunews/jktc
    public function jktc()
    {
        $hjdevice = \app\admin\model\wu\Hjdevice::get(3);
        if (!$hjdevice) {
            $this->error("无油量溢位與馬達運作監控裝置！");
        }

        $notifyoption = \app\admin\model\wu\Notifyoption::get(1);
        if (!$notifyoption) {
            $this->error("无设置！");
        }

//        if ($notifyoption->jkgc_tzswitch == 0) {
//            $this->error("監控感測通知已关闭！");
//        }


        $time = 0; // 不运转持续时间 分鐘
        //'10秒','20秒','30秒'
        $from = date("Y-m-d H:i:s", time() - 60);
        //FE09 --- 10 秒無異常命令，則顯示”接收裝置正常運作中”
        $state9list = \app\admin\model\wu\Hjdevicelog::where("commandtype", "FE09")
            ->where('create_time', '>', $from)
            ->where('hjdevice_id', 3)
            ->order('id desc')
            ->select();


        foreach ($state9list as $row) {
            $value = intval($row->value1);
            $ycgj = "";
            switch ($value) {
                default:
                    break;
                case 0;
                    $ycgj = "溢位裝置 A 異常";
                    break;
                case 1;
                    $ycgj = "溢位裝置 B 異常";
                    break;
                case 2;
                    $ycgj = "馬達量測電流裝置 A-1 異常";
                    break;
                case 3;
                    $ycgj = "馬達量測電流裝置 A-2 異常";
                    break;
                case 4;
                    $ycgj = "馬達量測電流裝置 B-1 異常";
                    break;
                case 5;
                    $ycgj = "馬達量測電流裝置 B-2 異常";
                    break;
            }

            if (!empty($ycgj)) {
                $news = new \app\admin\model\wu\News;
                $news->name = "[監控感測]" . $ycgj;
                $news->type = "其它";
                $news->save();
            }

        }

        $this->success("ok");
    }

    //Line通知,每分钟检查一次
    //http://wu.test/api/wunews/linenotify
    public function linenotify()
    {
        set_time_limit(0); //执行时间无限
        ini_set('memory_limit', '-1'); //内存无限

        //周末不通知
        $isweekend = 0;
        $a = date('w', time());
        if ($a == 6 || $a == 0) {
            $isweekend = 1;
        }

        $from = date("Y-m-d H:i:s", time() - 60);
        if ($a == 1 && strcmp(date("H:i", time()), "00:01") == 0) {
            //如果是周一 且是当天的第一分钟，需要回2天
            $from = date("Y-m-d H:i:s", time() - 2 * 3600 * 24);
        }
        $newslist = \app\admin\model\wu\News::where('createtime', '>', $from)->where('state', '0')->select();

        $notifyoption = \app\admin\model\wu\Notifyoption::get(1);
        if (!$notifyoption) {
            $this->error("无设置！");
        }

        //每分钟只处理一条溫濕度或马达的报警
        $wsdtz = 0;
        $mayz = 0;

        foreach ($newslist as &$row) {
           //'庫存不足','溫濕度通知','馬達運轉','其它'
            $issend = false;
            if ($row->type == '庫存不足') {
                if ($notifyoption->kc_tzswitch == 0)
                    continue;

                if ($isweekend && $notifyoption->kc_zmtzswitch) {
                    continue;
                }
                $issend = $this->line_message_send($notifyoption->kc_notifyusers, $row->name." [{$row->createtime}]");
            } else if ($row->type == '溫濕度通知' && $wsdtz == 0) {
                if ($notifyoption->wsd_tzswitch == 0)
                    continue;
                if ($isweekend && $notifyoption->wsd_zmtzswitch) {
                    continue;
                }
                //溫濕度通知頻率 ('1小時','3小時','6小時','12小時','1天')
                $t = 3600;
                if ($notifyoption->wsd_tzpl == "3小時") {
                    $t = 3600 * 3;
                } else if ($notifyoption->wsd_tzpl == "6小時") {
                    $t = 3600 * 6;
                } else if ($notifyoption->wsd_tzpl == "12小時") {
                    $t = 3600 * 12;
                } else if ($notifyoption->wsd_tzpl == "1天") {
                    $t = 3600 * 24;
                }

                $msg = $row->name." [{$row->createtime}]";
                $from1 = date("Y-m-d H:i:s", time() - $t);//1小時内没有发送过
                $newslist2 = \app\admin\model\wu\News::where('createtime', '>', $from1)->where('type', '溫濕度通知')->where('state', '1')->select();
                if ($newslist2) {
                    continue;
                }

                $issend = $this->line_message_send($notifyoption->wsd_notifyusers, $msg);
                if ($issend) {
                    $wsdtz = 1;
                }

            } else if ($row->type == '馬達運轉'  && $mayz == 0) {
                if ($notifyoption->md_tzswitch == 0)
                    continue;
                if ($isweekend && $notifyoption->md_zmtzswitch) {
                    continue;
                }
                //('10分鐘','20分鐘','30分鐘','1小時')
                $t = 60 * 10;
                if ($notifyoption->md_tzpl == "20分鐘") {
                    $t = 60 * 20;
                } else if ($notifyoption->md_tzpl == "30分鐘") {
                    $t = 60 * 30;
                } else if ($notifyoption->md_tzpl == "1小時") {
                    $t = 60 * 60;
                }

                $from1 = date("Y-m-d H:i:s", time() - $t);//10分鐘内没有发送过
                $newslist2 = \app\admin\model\wu\News::where('createtime', '>', $from1)->where('type', '馬達運轉')->where('state', '1')->select();
                if ($newslist2) {
                    continue;
                }

                $issend = $this->line_message_send($notifyoption->md_notifyusers, $row->name." [{$row->createtime}]");
                if ($issend) {
                    $mayz = 1;
                }
            } else if ($row->type == '其它') {
                if ($notifyoption->jkgc_tzswitch == 0)
                    continue;

                if ($isweekend && $notifyoption->jkgc_zmtzswitch) {
                    continue;
                }

                if (strpos($row->name, '[製程工序]')!== false ) {
                    $issend = $this->line_message_send($notifyoption->zld_notifyusers, $row->name." [{$row->createtime}]");
                } else {
                    //('10分鐘','20分鐘','30分鐘','1小時')
                    $t = 60 * 10;
                    if ($notifyoption->jkgc_tzpl == "20分鐘") {
                        $t = 60 * 20;
                    } else if ($notifyoption->jkgc_tzpl == "30分鐘") {
                        $t = 60 * 30;
                    } else if ($notifyoption->jkgc_tzpl == "1小時") {
                        $t = 60 * 60;
                    }

                    $from1 = date("Y-m-d H:i:s", time() - $t);//10分鐘内没有发送过
                    $newslist2 = \app\admin\model\wu\News::where('createtime', '>', $from1)->where('type', '其它')->where('name', 'LIKE', '%[製程工序]%')->where('state', '1')->select();
                    if ($newslist2) {
                        continue;
                    }
                    $issend = $this->line_message_send($notifyoption->jkgc_notifyusers, $row->name." [{$row->createtime}]");
                }

            }

            if ($issend) {
                $row->state = 1;
                $row->save();
            }
        }

        $this->success("ok");
    }

    //http://wu.test/api/wunews/line_message_send?userId=Ua2b67a5b7ac9d3923a9ec04cc6dc7250&msg=12333
    //https://wu.megotw.com/api/wunews/line_message_send?userId=Ua2b67a5b7ac9d3923a9ec04cc6dc7250&msg=12333
    public function line_message_send($adminIds, $msg)
    {
        $channelAccessToken = "YfzDaRTTdJifl1Rrmoo8/ZV8dgYy6LoqLTkw19TYuiKVJJRQ5UybLrOcl/UNIkDmyW4oJdm319Ue1fswhm7jfihljFQKYdYCkezyJyeTfxaTR5DKWlDamKTY+NhvloWnWL/pPpgp2jhEFO1hVA7bFAdB04t89/1O/w1cDnyilFU=";
        $userIds = [];
        $list = \app\admin\model\Admin::where('id', 'in', $adminIds)->field('id, line_userid')->select();

        foreach ($list as $row) {
            $userIds[] = $row->line_userid;
        }
        if (count($userIds) < 1) {
            return false;
        }

        $payload = [
            'to' => $userIds,
            'messages' => [
                [
                    'type' => 'text',
                    'text' => $msg
                ]
            ]
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://api.line.me/v2/bot/message/multicast');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $channelAccessToken
        ]);
        $linesend = curl_exec($ch);

        $message = "err";
        //没有返回值就是发送成功了
        if ($linesend) {
            $linesend = json_decode($linesend, true);
            if (isset($linesend['message']) && strlen($linesend['message']) > 6) {
                //发送失败
                $message = $linesend['message'];
            } else {
                //发送成功
                $message = "ok";
            }
        } else {
            //网络异常  返回值是0， 应该是成功的
            $message = curl_errno($ch);
        }
        curl_close($ch);

        return true;
    }

}





